<template>
    <div>
        <el-button type="primary" @click="showDialog">新增请假</el-button>
        <el-dialog v-model="dialogVisible" title="新增请假" style="min-width: 650px;">
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
                class="demo-ruleForm">
                <el-form-item label="请假理由" prop="reson">
                    <el-input v-model="ruleForm.reson" />
                </el-form-item>
                <el-form-item label="开始时间" prop="start">
                    <el-date-picker v-model="ruleForm.start" type="datetime" placeholder="选择开始时间" />
                </el-form-item>
                <el-form-item label="结束时间" prop="end">
                    <el-date-picker v-model="ruleForm.end" type="datetime" placeholder="选择结束时间" />
                </el-form-item>
                <el-form-item label="附件" prop="extend">
                    <el-upload :limit="2" action="/api/upload" name="file" v-model:file-list="fileList"
                        list-type="picture-card" :auto-upload="false" ref="uploadRef" :on-exceed="handleExceed"
                        :on-success="success">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <template #file="{ file }">
                            <div>
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                        <el-icon><zoom-in /></el-icon>
                                    </span>
                                    <span v-if="!disabled" class="el-upload-list__item-delete"
                                        @click="handleDownload(file)">
                                        <el-icon>
                                            <Download />
                                        </el-icon>
                                    </span>
                                    <span v-if="!disabled" class="el-upload-list__item-delete"
                                        @click="handleRemove(file)">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </span>
                                </span>
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">添加</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog v-model="previewVisible" class="preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { reactive, ref } from 'vue';
import { genFileId } from 'element-plus';
import type { FormInstance, UploadUserFile, UploadProps, UploadRawFile, UploadInstance } from 'element-plus';
import { addLeave } from '@/serveice/leavelist';
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

let emits = defineEmits(['addList'])
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
    reson: '',  //请假理由
    start: '',  //开始时间
    end: '',  //结束时间
    extend: '' //附件
});
const dialogVisible = ref(false);//控制对话框显示
const rules = reactive({
    reson: [
        { required: true, message: '请假理由不能为空', trigger: 'blur' },
        { min: 2, max: 12, message: '请假理由长度2-12位', trigger: 'blur' }
    ],
    start: [
        { required: true, message: '开始时间不能为空', trigger: 'blur' },
        { validator: checkStart, trigger: 'change' }
    ],
    end: [
        { required: true, message: '结束时间不能为空', trigger: 'blur' },
        { validator: checkEnd, trigger: 'change' }
    ],
});
const fileList = ref<UploadUserFile[]>([
    //选择图片的集合
]);
const uploadRef = ref<UploadInstance>();
const disabled = ref(false); //是否可用
const dialogImageUrl = ref(""); //图片
const previewVisible = ref(false); //图片放大的层级
const successList: any = ref([])

const handleExceed: UploadProps['onExceed'] = (files) => {
    fileList.value.shift();
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}


const success = async (res: any) => {
    //图片上传成功的回调函数
    console.log(35);

    console.log(res);
    if (res.code == 200) {
        successList.value.push(res.url);//图片的地址
        if (successList.value.length == fileList.value.length) {
            //说明图片全部上传完毕
            let { data } = await addLeave({
                ...ruleForm,
                extend: successList.value.join(",")
            });
            //console.log(res);
            if (data.code == 200) {
                resetForm(ruleFormRef.value);
                //res.data.info  新增的数据的集合
                // list.value = [...list.value,...res.data.info];
                emits("addList", ...data.list);
            }
        }
    }
}
function handleDownload(file: any) {
    console.log(1);
}

function handlePictureCardPreview(file: any) {
    dialogImageUrl.value = file.url!;
    previewVisible.value = true;
}
function handleRemove(file: any) {
    fileList.value = fileList.value.filter((item: any) => item !== file);
}


function checkStart(rule: any, value: any, callback: any) {
    if (ruleForm.end) {
        let endDate = new Date(ruleForm.end);
        let startDate = new Date(value);
        if (startDate > endDate) {
            return callback(new Error('开始时间不能大于结束时间'))
        }
    }
    callback()
}

function checkEnd(rule: any, value: any, callback: any) {
    if (ruleForm.start) {
        let startDate = new Date(ruleForm.start);
        let endDate = new Date(value);
        if (startDate > endDate) {
            return callback(new Error('结束时间不能小于开始时间'))
        }
    }
    callback()
}

function showDialog() {
    dialogVisible.value = true//显示对话框
}

function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            if (fileList.value.length) {
                //有图片
                uploadRef.value!.submit(); //手动上传
            } else {
                //没有图片
                let { data } = await addLeave({
                    ...ruleForm
                })
                //console.log(res);
                if (data.code == 200) {
                    resetForm(ruleFormRef.value);
                    //res.data.info  新增的数据的集合
                    emits("addList", ...data.list);
                }
            }
        } else {
            console.log('error submit!')
            return false
        }
    })
}

function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields();
    uploadRef.value!.clearFiles()
    dialogVisible.value = false
}
</script>
<style lang='less' scoped>
:deep(.preview) {
    display: inline-block;
    width: auto;
    left: 50%;
    transform: translateX(-50%);

    .el-dialog__body {

        img {
            max-width: 100%;
        }
    }


}
</style>